<?php
namespace app\api\controller;

use app\api\model\ConfigPersonal;
use app\api\model\UserImg;
use think\Db;
use app\api\model\VolleyDesc as Balance;
use app\api\model\Task;
use app\api\model\ConfigSystem as Config;
use Vectorface\Whip\Whip;
use app\api\model\Code;
use app\api\model\Labels;
use app\api\model\Reg as RegModel;
use app\api\model\YaoqingRecords as Income;
use app\api\model\User;
use GatewayClient\Gateway;
use app\api\model\UserMaterialVerify;
use app\api\model\RecycleReview;
use app\api\model\Privatechat;
use app\service\UserDevice;
use app\service\Token;

class Reg extends Common
{
    public function index()
    {
        $bindway = 2;
        $post = input('post.');
        $time = time();
        $datetime = datetime();
        $config = (new Config)->index('check');
        $avatar = '';
        if ($config['check_avatar'] && $post['sex'] == '男') {
            if (isset($post['head']) && $post['head']) {
                $avatar = $post['head'];
                unset($post['head']);
            }
        }

        if (!isset($post['name']) || !$post['name']) {
            $post['name'] = suiji2();
            // return json(['code' => 205, 'msg' => '请先输入昵称']);
        } else {
            $nickExist = Db::name('user')->where(['name'=>$post['name'], 'reg'=>1])->count();
            if ($nickExist) {
                return $this->miss('昵称已被占用');
            }
        }
        
        $nickname = '';
        if ($config['check_edit_nickname']) {
            if (isset($post['name']) && $post['name']) {
                $nickname = $post['name'];
                // $post['name'] = '昵称审核中';
            }
        }

        if (isset($post['head']) && $post['head']) {
            $head = explode('.', $post['head']);
            $post['head_100'] = $head[0] . '_thumb.' . $head[1];
            $post['head_300'] = $head[0] . '_thumb.' . $head[1];
            $post['head_portrait'] = $post['head'];
        } else {
            $sex= $post['sex'] ?? '男';
            $dir = $sex == '男' ? 'male' : 'female';
            $post['head_100'] = $post['head_300'] = $post['head_portrait'] = '/public/style/api/img/' . $dir . '/' . mt_rand(1,20) . '.jpg';
        }


        //唯一邀请码
        // for ($i = 2; $i > 1; $i++) {
        //     $len = 5;
        //     $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //     mt_srand(10000000 * (double)microtime());
        //     for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
        //         $str .= $chars[mt_rand(0, $lc)];
        //     }
        //     $yqm = $str;

        //     $test = Db::name('user')->where(['yqm' => $yqm])->find();
        //     if (!$test) {
        //         $i = 0;
        //     }
        // }
        // $post['yqm'] = $yqm;
        
        //新邀请码
        $inviteCode = $this->generateUniqueInviteCode();
        $post['yqm'] = $inviteCode;
        
        $post['yqr'] = $post['send_code'] ?? '';
        unset($post['head'], $post['send_code']);

        if (isset($post['phone']) && !$post['phone']) {
            unset($post['phone']);
        }

        // $field = ($field = ($field = isset($post['phone']) ? 'phone' : '') ? $field : ($field = isset($post['wechat']) ? 'wechat' : '')) ? $field : ($field = isset($post['qq_openID']) ? 'qq_openID' : '');
        // $param = ($param = ($param = $post['phone'] ?? '') ? $param : ($param = $post['wechat'] ?? '')) ? $param : ($param = $post['qq_openID'] ?? '');
        $param = $post['phone'] ?? '';
        $field = 'phone';
        if (!$param) {
            $param = $post['wechat'] ?? '';
            $field = 'wechat';
        }
        if (!$param) {
            $param = $post['qq_openID'] ?? '';
            $field = 'qq_openID';
        }
        $email = false;
        if (!$param) {
            $email = $param = $post['email'] ?? '';
            unset($post['email']);
        }
        if (!$param) return json(['code' => 205, 'msg' => '请选择注册一种类型']);

        if ($email) {
            $user = Db::name('user_auth')->where(['type' => 1, 'account'=>$email, 'state' => 1])->find();
        } else {
            $user = Db::name('user')->where([$field => $param])->find();
        }
        if ($user) return json(['code' => 204, 'msg' => '账号已注册']);

        if (!isset($post['sex']) || !$post['sex']) {
            return json(['code' => 205, 'msg' => '请先选择性别']);
        }
    
        if (isset($post['device_id']) && !$post['device_id']) {
            return json(['code' => 205, 'msg' => '未获取到设备信息']);
        }
    
        /*$result = Db::name('user')->where(['device_id' => $post['device_id']])->value('id');
        if ($result) {
            return json(['code' => 205, 'msg' => '此设备已注册过账号']);
        }*/

        if ($post['sex'] == '男') {
            //if($post['yqr'] == "会员"){
            if(isset($post['user_id'])) {
                if ($post['user_id']) {
                    $id = $post['user_id'];
                    //$post['yqr'] = '';
                }
            }
            //$post['is_identity_authentication'] = 2;
            //$post['attestation'] = 1;
            $post['wanshang'] = 1;
            $post['reg'] = 1;
        }

        unset($post['user_id']);

        if (isset($post['wechat']) && !$post['wechat']) {
            unset($post['wechat']);
        }

        if (isset($post['qq_openID']) && !$post['qq_openID']) {
            unset($post['qq_openID']);
        }

        if (isset($post['birthday'])) {
            $post['age'] = countage($post['birthday']);
        }
        // $post['age'] = 38;

        $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'templete', 'user', 'invite', 'push']]])->column('title, content');

        if (isset($id) && $id) {
            exit;
            //Db::name('user')->where(['id' => $id])->update($post);
        } else {//判断注册账号
            $firstyq = true;
            if(isset($post['phone'])){//手机号必传的项
                //判断手机号之前是否绑定过邀请人
                 $oldyqr = recycleyqr($post['phone'])?:'';
                 if($oldyqr){//原手机号已注销 同一手机号在注册 之前绑定的邀请人不变更
                     $firstyq = false;
                     $haslogoff1 = Db::name('recycle_user')->where(['phone'=>$post['phone'],'channel'=>1])->order('id desc')->find();
                     if ($haslogoff1) {//存在手机号注销
                         $recycleUser = Db::name('user')->where(['id'=>$haslogoff1['user_id'], 'delete_time'=>['>', 0]])->find();
                         if ($recycleUser) {//基于原账号进行用户信息更新
                             //此处判断之前是否存在邀请人
                             if($oldyqr){//存在旧的邀请人
                                 if($post['yqr']){
                                     //echo $oldyqr;die;
                                     if($oldyqr===$post['yqr']){//填写的邀请人和以前一致不处理
                                     }else{
                                         return json(['code' => 205, 'msg' => "该账号已绑定邀请码【{$oldyqr}】请填写此码或留空"]);
                                     }
                                 }else{
                                     $post['yqr']=$oldyqr;
                                 }
                             }
                             $resumeUserUpdate = [
                                 'phone'=>$post['phone'],
                                 'delete_time'=>0,
                                 'register_datetime'=>$datetime,
                                 'last_login_datetime'=>$datetime,
                                 'register_datetime'=>$datetime,
                                 'last_login_time'=>$time,
                                 'yqr'            =>$post['yqr'],
                                 'name'              => $post['name']
                             ];
                             if (isset($post['head_100'])) {
                                 $resumeUserUpdate['head_100'] = $post['head_100'];
                                 $resumeUserUpdate['head_300'] = $post['head_300'];
                                 $resumeUserUpdate['head_portrait'] = $post['head_portrait'];
                             }
                             $resumeUser = Db::name('user')->where(['id'=>$recycleUser['id']])->update($resumeUserUpdate);
                             if ($resumeUser && $post['sex']=='女') {//女用户注册发放金豆
                                $id = $recycleUser['id'];
                                //$this->giveRegisterBeans($id);
                             }
                             $tokenData = array(
                                 'userid' => $recycleUser['id'],
                                 'time' => $time,
                             );
                             $token = Token::createToken($tokenData);
                             if($token['status']==200){
                                 $token = $token['token'];
                             }else{
                                 $token = '';
                             }

                             return json(['code' => 200, 'msg' => '注册成功', 'id' => $recycleUser['id'], 'token' => $token]);
                         }
                     }
                 }else{//不同手机号注册判断设备 若同一设备绑定的邀请人不变更
                     if(!isset($post['device_id'])){
                         return json(['code' => 205, 'msg' => "设备信息获取失败，请重试！"]);
                     }
                     //不同手机号判断设备是否有注册记录
                     $infodevice=Db::name('user')->where(['device_id' => $post['device_id'],'reg'=>1])->field('id, yqr')->order('id desc')->find();
                     if($infodevice){//设备存在注册
                        $oldyqr=$infodevice['yqr'];
                        $firstyq = true;
                         if($oldyqr){//存在旧的邀请人
                             if($post['yqr']){
                                 //echo $oldyqr;die;
                                 if($oldyqr===$post['yqr']){//填写的邀请人和以前一致不处理
                                 }else{
                                     return json(['code' => 205, 'msg' => "该设备已绑定邀请码【{$oldyqr}】请填写此码或留空"]);
                                 }
                             }else{
                                 $post['yqr']=$oldyqr;
                             }
                         }
                     }
                 }
    
                if (isset($post['code'])) {
                    $verify = Code::verifyCode($post['phone'], $post['code'], 1);
                    if ($verify['code'] == 400) {
                        return $this->miss($verify['msg']);
                    }
                    unset($post['code']);
                }
            }
            if(isset($post['name'])){
                if(ishasPhoneNumber($post['name'])){
                    exit(json_encode(['code' => 400, 'msg' => '昵称禁止输入手机号']));
                }
            }
            $whip = new Whip();
            $clientAddress = $whip->getValidIpAddress();
            if ($post['yqr']) {
                $result = Db::name('user')->where(['yqm' => $post['yqr'], 'reg'=>1, 'delete_time'=>0])->find();
                if (!$result) {
                    $post['yqr'] = '';
                    //return json(['code' => 205, 'msg' => '邀请码不存在']);
                }

                /*if (!preg_match('/^[a-zA-Z\s]+$/',$post['yqr'])) {
                    $yqm = Db::name('user')->where(['id' => $post['yqr']])->value('yqm');
                    if (!$yqm) return json(['code' => 205, 'msg' => '邀请码错误']);
                    $post['yqr'] = $yqm;
                }

                $result = Db::name('user')->where(['yqm' => $post['yqr']])->find();

                if (!$result) {
                    $result = Db::name('code')->where(['code' => $post['yqr'], 'type' => 1, 'state' => 0])->find();
                    if (!$result) return json(['code' => 205, 'msg' => '邀请码不存在']);

                    Db::name('code')->where(['id' => $result['id']])->setField('state', 1);
                }*/
            } else {

                // $prev_time = time() - 1800;
                // $s1 = Db::name('proxy_visit_records')->where(['ip' => $clientAddress, 'create_time' => ['gt', $prev_time]])->order('create_time desc')->value('user_id');
                // if ($s1) {
                //     $s1_yqm = Db::name('user')->where(['id' => $s1])->value('yqm');
                //     if ($s1_yqm) {
                //         $post['yqr'] = $s1_yqm;
                //         $bindway = 1;
                //     }
                // }
                $bindway = 1;
            }

            if ($post['sex'] == '男') {
                $post['free_chat'] = $config['free_chat'];
                $post['free_voice'] = $config['free_voice'];
                $post['free_video'] = $config['free_video'];
            }
            if ($post['sex'] == '女') {//女用户注册默认隐藏距离
                $post['hide_distance'] = 1;
            }
            if (isset($post['labels'])) {
                $labels = $post['labels'];
                unset($post['labels']);
            }
    
            if ($post['yqr'] === null) {
                $post['yqr'] = '';
            }

            if ($post['yqr']) {
                $post['invite_time'] = $time;
            }
            $post['last_login_time'] = $time;

            if (isset($post['sandbox'])) {
                unset($post['sandbox']);
            }
            $post['entertainment'] = 0;
            // if (isset($post['entertainment'])) {
            //     unset($post['entertainment']);
            // }
            $id = Db::name('user')->insertGetId($post);
            if ($id && $post['sex']=='女') {//女用户注册发放金豆
                //$this->giveRegisterBeans($id);
            }
        }

        if ($id) {
            if ($email) {
                Db::name('user_auth')->insert([
                    'user_id'=>$id,
                    'type'=>1,
                    'account'=>$email,
                    'state'=>1,
                    'create_time'=>$time
                ]);
            }
            if (isset($labels)) {
                Labels::edit($labels, $id, 2);
            }

            if ($avatar) {
                UserMaterialVerify::index(1, $id, $avatar);
            }else{
                // if ($post['sex'] == '女') {
                    UserMaterialVerify::index(1, $id, $post['head_portrait'], 0, 1);
                // }
                UserImg::create([
                    'user_id' => $id,
                    'pic' => json_encode([$post['head_portrait']]),
                    'picthumb' => json_encode([$post['head_300']]),
                    'is_avatar' => 1,
                ]);
            }
            if ($nickname) {
                UserMaterialVerify::index(3, $id, $nickname);
            }

            $response = ConfigPersonal::createData($id, $post['sex']);
            $result = $response->getData();
            if ($result['code'] == 400) {
                return $response;
            }

            $ids = Db::name('push_category')->where(['is_hidden' => 0])->column('id');
            if ($ids) {
                $contain = [];
                foreach ($ids as $v) {
                    $contain[] = ['cid' => $v, 'user_id' => $id];
                }
                Db::name('push_member')->insertAll($contain);
            }

            $money = intval($config['reg']);
            if ($money) {
                Balance::index($id, $money, '新用户注册奖励', 1);
            }
            RegModel::checkDevice($post['device_id'], $id);

            // 上级奖励
            if ($post['yqr'] && $firstyq) {
                $user = Db::name('user')->where(['yqm' => $post['yqr']])->find();
                if ($user) {
                    //Db::name('ranking_records')->insert(['types' => 8, 'user_id' => $user['id'], 'to_user' => $id, 'count' => 1, 'create_time' => time()]);

                    Db::name('user')->where(['id' => $user['id']])->setInc('invite_count');
                    Db::name('user')->where(['id' => $id])->update(['entertainment'=>$user['entertainment']]);

                    if ($user['entertainment'] == 2 && $post['sex'] == '女') {
                        Privatechat::notice($id, '你当前为交友身份（真实交友），只能设置比较低的聊天价格，如果错了可以联系客服更改');
                    }

                    //Db::name('user')->where(['id' => $id])->setField('invite_time', time());

                    // 任务
                    Task::finish('invite', $user['id']);

                    if ($user['proxy'] + 0) {
                        $hongbao = $config['hongbao'];

                        $hongbao = explode(',',$hongbao);

                        $hongbao[1] = $hongbao[1] ?? $hongbao[0];

                        $money = mt_rand($hongbao[0],$hongbao[1]);

                        if ($money + 0) {
                            Income::index($user['id'], $id, $money, '邀请奖励收益', 1);
                        }
                    }
                    RegModel::parentSay($id, $post['sex'], $post['yqr']);
                    User::bindParentWalfare($user['id'], $id, $post['device_id'], $clientAddress);
                    User::bindParent($user['id'], $id, $bindway);
                }
            }

            /*$request = request();
            $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

            $kefu = intval($config['id']);

            if ($kefu) {
                $field = $post['sex'] == '男' ? 'welcome_male' : 'welcome_female';
                $datas = [
                    'userid' => $kefu,
                    'touserid' => $id,
                    'type' => 0,
                    'content' => $config[$field],
                    'single' => 1
                ];
                curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
            }*/


            
            $user = Db::name('user')->master()->find($id);
            // User::welfare($user);
            User::pushchat($user);
            User::regNotice($user);
        }


        $tokenData = array(
            'userid' => $id,
            'time' => $time,
        );
        UserDevice::InsertS($id, $post['device_id']);
        $token = Token::createToken($tokenData);
        if($token['status']==200){
            $token = $token['token'];
        }else{
            $token = '';
        }

        return json(['code' => 200, 'msg' => '注册成功', 'id' => $id, 'token' => $token]);
    }

    public function quick()
    {
        if(!input('z')){
            exit;
        }
        $post = getRsaPostParamArr2();
        // $post = input();
        $time = time();
        if(isset($post['time']) && $post['time']){
            if($post['time'] + 10 < $time){
                return json(['code' => 500, 'msg' => '网络超时']);
            }
        }else{
            return json(['code' => 500, 'msg' => '登录失败']);
        }
        unset($post['time']);
        if($post['phone'] && $post['device_id']){
            $post['phone'] = str_replace('+86','',$post['phone']);
            $user = User::get(['phone' => $post['phone'], 'reg' => 1]);
            if($user){
                if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
                    return $this->miss('账号被封禁，解封时间：' . $user['banned_end_time'],201);
                }
                // if ($user['last_login_time'] < strtotime('2023-01-01')) {
                //     return $this->miss('账号已注销');
                // }
                

                $updates = [
                    'id' => $user->id,
                    'is_banned' => 0,
                    'banned_end_time' => null,
                    'is_online' => 1,
                    'last_login_datetime' => date('Y-m-d H:i:s'),
                    'device_id' => $post['device_id'],
                    'last_login_time' => $time
                ];
        
                //if ($user['remote']) {
                    $updates['role'] = 0;
                //}

                User::update($updates);

                if ($post['device_id']) {
                    $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $post['device_id']]]);
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user->id, $message);
                }

                cache('video_' . $user->id, NULL);

                User::bindPrev($user);
                User::welfare($user);
                User::pushchat($user);
                RecycleReview::unRecycle($user->id);

                $tokenData = array(
                    'userid' => $user->id,
                    'time' => $time,
                    'sex' => $user->sex
                );
                UserDevice::InsertS($user->id, $post['device_id']);
                $token = Token::createToken($tokenData);
                if($token['status']==200){
                    $token = $token['token'];
                }else{
                    $token = '';
                }


                return $this->pass(['id' => $user->id, 'sex' => $user->sex, 'wanshang' => $user->wanshang, 'token' => $token], 'result');
            }elseif(isset($post['sex']) && $post['sex']){

                
                $config = (new Config)->index('check');
                $avatar = '';
                if ($config['check_avatar']) {
                    if (isset($post['head']) && $post['head']) {
                        $avatar = $post['head'];
                        unset($post['head']);
                    }
                }
                $nickname = '';
                if ($config['check_edit_nickname']) {
                    if (isset($post['name']) && $post['name']) {
                        $nickname = $post['name'];
                        unset($post['name']);
                    } else {
                        $post['name'] = suiji2();
                    }
                }

                if (isset($post['head']) && $post['head']) {
                    $head = explode('.', $post['head']);
                    $post['head_100'] = $head[0] . '_thumb.' . $head[1];
                    $post['head_300'] = $head[0] . '_thumb.' . $head[1];
                    $post['head_portrait'] = $post['head'];
                } else {
                    $sex = $post['sex'] ?? '男';
                    $dir = $sex == '男' ? 'male' : 'female';
                    $post['head_100'] = $post['head_300'] = $post['head_portrait'] = '/public/style/api/img/' . $dir . '/' . mt_rand(1,20) . '.jpg';
                }


                //唯一邀请码
                for ($i = 2; $i > 1; $i++) {
                    $len = 5;
                    $chars = "0123456789";
                    mt_srand(10000000 * (double)microtime());
                    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
                        $str .= $chars[mt_rand(0, $lc)];
                    }
                    $yqm = $str;

                    $test = Db::name('user')->where(['yqm' => $yqm])->find();
                    if (!$test) {
                        $i = 0;
                    }
                }
                if(!isset($post['name']) || !$post['name']){
                    $post['name'] = '用户' . rand(10000, 99999);
                }else{
                    if(ishasPhoneNumber($post['name'])){
                        exit(json_encode(['code' => 400, 'msg' => '昵称禁止输入手机号']));
                    }
                }
                $post['yqm'] = $yqm;
                if ($post['sex'] == '男') {
                    $post['wanshang'] = 1;
                    $post['reg'] = 1;
                }
                $post['yqr'] = $post['send_code'] ?? '';
                unset($post['head'], $post['send_code']);


                $firstyq = true;
                // $oldyqr = recycleyqr($post['phone']);
                // if($oldyqr){
                //     $post['yqr'] = $oldyqr;
                //     $firstyq = false;
                // }

                if (isset($post['birthday'])) {
                    $post['age'] = countage($post['birthday']);
                }

                $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'templete', 'user', 'invite', 'push']]])->column('title, content');

                if ($post['yqr']) {
                    $result = Db::name('user')->where(['yqm' => $post['yqr']])->find();
                    if (!$result) {
                        $post['yqr'] = '';
                    }

                } else {
                    $whip = new Whip();
                    $clientAddress = $whip->getValidIpAddress();

                    $prev_time = time() - 1800;
                    $s1 = Db::name('proxy_visit_records')->where(['ip' => $clientAddress, 'create_time' => ['gt', $prev_time]])->order('create_time desc')->value('user_id');
                    if ($s1) {
                        $s1_yqm = Db::name('user')->where(['id' => $s1])->value('yqm');
                        if ($s1_yqm) {
                            $post['yqr'] = $s1_yqm;
                        }
                    }
                }



                if ($post['sex'] == '男') {
                    $post['free_chat'] = $config['free_chat'];
                    $post['free_voice'] = $config['free_voice'];
                    $post['free_video'] = $config['free_video'];
                }
                if (isset($post['labels'])) {
                    $labels = $post['labels'];
                    unset($post['labels']);
                }
        
                if ($post['yqr'] === null) {
                    $post['yqr'] = '';
                }

                if ($post['yqr']) {
                    $post['invite_time'] = $time;
                }

                $post['last_login_time'] = $time;

                $post['entertainment'] = 0;
                // if (isset($post['entertainment'])) {
                //     unset($post['entertainment']);
                // }

                $id = Db::name('user')->insertGetId($post);

                if ($id) {
                    $post['id'] = $id;
                    if (isset($labels)) {
                        Labels::edit($labels, $id, 2);
                    }
                    User::regNotice($post);
                    RegModel::checkDevice($post['device_id'], $id);

                    if ($avatar) {
                        UserMaterialVerify::index(1, $id, $avatar);
                    }else{
                        UserImg::create([
                            'user_id' => $id,
                            'pic' => json_encode([$post['head_portrait']]),
                            'picthumb' => json_encode([$post['head_300']]),
                            'is_avatar' => 1,
                        ]);
                    }
                    if ($nickname) {
                        UserMaterialVerify::index(3, $id, $nickname);
                    }

                    $response = ConfigPersonal::createData($id, $post['sex']);
                    $result = $response->getData();
                    if ($result['code'] == 400) {
                        return $response;
                    }

                    $ids = Db::name('push_category')->where(['is_hidden' => 0])->column('id');
                    if ($ids) {
                        $contain = [];
                        foreach ($ids as $v) {
                            $contain[] = ['cid' => $v, 'user_id' => $id];
                        }
                        Db::name('push_member')->insertAll($contain);
                    }

                    $money = intval($config['reg']);
                    if ($money) {
                        Balance::index($id, $money, '新用户注册奖励', 1);
                    }

                    // 上级奖励
                    if (isset($post['yqr']) && $post['yqr'] && $firstyq) {
                        $user = Db::name('user')->where(['yqm' => $post['yqr']])->find();
                        if ($user) {
                            //Db::name('ranking_records')->insert(['types' => 8, 'user_id' => $user['id'], 'to_user' => $id, 'count' => 1, 'create_time' => time()]);

                            Db::name('user')->where(['id' => $user['id']])->setInc('invite_count');
                            Db::name('user')->where(['id' => $id])->update(['entertainment'=>$user['entertainment']]);

                            //Db::name('user')->where(['id' => $id])->setField('invite_time', time());

                            // 任务
                            Task::finish('invite', $user['id']);

                            if ($user['proxy'] + 0) {
                                $hongbao = $config['hongbao'];

                                $hongbao = explode(',',$hongbao);

                                $hongbao[1] = $hongbao[1] ?? $hongbao[0];

                                $money = mt_rand($hongbao[0],$hongbao[1]);

                                if ($money + 0) {
                                    Income::index($user['id'], $id, $money, '邀请奖励收益', 1);
                                }
                            }

                            RegModel::parentSay($id, $post['sex'], $post['yqr']);
                        }
                    }

                    /*$request = request();
                    $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

                    $kefu = intval($config['id']);

                    if ($kefu) {
                        $field = $post['sex'] == '男' ? 'welcome_male' : 'welcome_female';
                        $datas = [
                            'userid' => $kefu,
                            'touserid' => $id,
                            'type' => 0,
                            'content' => $config[$field],
                            'single' => 1
                        ];
                        curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                    }*/
                }
                $tokenData = array(
                    'userid' => $id,
                    'time' => $time,
                );
                $token = Token::createToken($tokenData);
                UserDevice::InsertS($id, $post['device_id']);
                if($token['status']==200){
                    $token = $token['token'];
                }else{
                    $token = '';
                }

                return json(['code' => 200, 'msg' => '注册成功', 'id' => $id, 'token' => $token]);
            }else{
                return json(['code' => 201, 'msg' => '请选择性别']);
            }
        }
    }
    public function quickb()
    {
        if(!input('z')){
            exit;
        }
        $post = getRsaPostParamArr();
        var_dump($post);exit;
        // $post = input();
        $time = time();
        if(isset($post['time']) && $post['time']){
            if($post['time'] + 10 < $time){
                return json(['code' => 500, 'msg' => '网络超时']);
            }
        }else{
            return json(['code' => 500, 'msg' => '登录失败']);
        }
        unset($post['time']);
        if($post['phone'] && $post['device_id']){
            $user = User::get(['phone' => $post['phone'], 'reg' => 1]);
            if($user){
                if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
                    return $this->miss('账号被封禁，解封时间：' . $user['banned_end_time'],201);
                }
                
                $updates = [
                    'id' => $user->id,
                    'is_banned' => 0,
                    'banned_end_time' => null,
                    'is_online' => 1,
                    'last_login_datetime' => date('Y-m-d H:i:s'),
                    'device_id' => $post['device_id'],
                ];
        
                //if ($user['remote']) {
                    $updates['role'] = 0;
                //}

                User::update($updates);

                if ($post['device_id']) {
                    $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $post['device_id']]]);
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user->id, $message);
                }

                cache('video_' . $user->id, NULL);

                User::bindPrev($user);

                return $this->pass(['id' => $user->id, 'sex' => $user->sex, 'wanshang' => $user->wanshang], 'result');
            }elseif($post['sex']){

                if (isset($post['head'])) {
                    $head = explode('.', $post['head']);
                    $post['head_100'] = $head[0] . '_thumb.' . $head[1];
                    $post['head_300'] = $head[0] . '_thumb.' . $head[1];
                    $post['head_portrait'] = $post['head'];
                } else {
                    $sex = $post['sex'] ?? '男';
                    $dir = $sex == '男' ? 'male' : 'female';
                    $post['head_100'] = $post['head_300'] = $post['head_portrait'] = '/public/style/api/img/' . $dir . '/' . mt_rand(1,20) . '.jpg';
                }


                //唯一邀请码
                for ($i = 2; $i > 1; $i++) {
                    $len = 5;
                    $chars = "0123456789";
                    mt_srand(10000000 * (double)microtime());
                    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
                        $str .= $chars[mt_rand(0, $lc)];
                    }
                    $yqm = $str;

                    $test = Db::name('user')->where(['yqm' => $yqm])->find();
                    if (!$test) {
                        $i = 0;
                    }
                }
                if(!isset($post['name']) || !$post['name']){
                    $post['name'] = '用户' . rand(10000, 99999);
                }
                $post['yqm'] = $yqm;
                if ($post['sex'] == '男') {
                    $post['wanshang'] = 1;
                    $post['reg'] = 1;
                }
                $post['yqr'] = $post['send_code'] ?? '';
                unset($post['head'], $post['send_code']);

                if (isset($post['birthday'])) {
                    $post['age'] = countage($post['birthday']);
                }

                $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'templete', 'user', 'invite', 'push']]])->column('title, content');

                if ($post['yqr']) {
                    $result = Db::name('user')->where(['yqm' => $post['yqr']])->find();
                    if (!$result) {
                        $post['yqr'] = '';
                    }

                } else {
                    $whip = new Whip();
                    $clientAddress = $whip->getValidIpAddress();

                    $prev_time = time() - 1800;
                    $s1 = Db::name('proxy_visit_records')->where(['ip' => $clientAddress, 'create_time' => ['gt', $prev_time]])->order('create_time desc')->value('user_id');
                    if ($s1) {
                        $s1_yqm = Db::name('user')->where(['id' => $s1])->value('yqm');
                        if ($s1_yqm) {
                            $post['yqr'] = $s1_yqm;
                        }
                    }
                }


                if ($post['sex'] == '男') {
                    $post['free_chat'] = $config['free_chat'];
                    $post['free_voice'] = $config['free_voice'];
                    $post['free_video'] = $config['free_video'];
                }
                if (isset($post['labels'])) {
                    $labels = $post['labels'];
                    unset($post['labels']);
                }
        
                if ($post['yqr'] === null) {
                    $post['yqr'] = '';
                }

                if ($post['yqr']) {
                    $post['invite_time'] = time();
                }


                $id = Db::name('user')->insertGetId($post);

                if ($id) {
                    if (isset($labels)) {
                        Labels::edit($labels, $id, 2);
                    }

                    UserImg::create([
                        'user_id' => $id,
                        'pic' => json_encode([$post['head_portrait']]),
                        'picthumb' => json_encode([$post['head_300']]),
                        'is_avatar' => 1,
                    ]);
                    $response = ConfigPersonal::createData($id, $post['sex']);
                    $result = $response->getData();
                    if ($result['code'] == 400) {
                        return $response;
                    }

                    $ids = Db::name('push_category')->where(['is_hidden' => 0])->column('id');
                    if ($ids) {
                        $contain = [];
                        foreach ($ids as $v) {
                            $contain[] = ['cid' => $v, 'user_id' => $id];
                        }
                        Db::name('push_member')->insertAll($contain);
                    }

                    $money = intval($config['reg']);
                    if ($money) {
                        Balance::index($id, $money, '新用户注册奖励', 1);
                    }

                    // 上级奖励
                    if (isset($post['yqr']) && $post['yqr']) {
                        $user = Db::name('user')->where(['yqm' => $post['yqr']])->find();
                        if ($user) {
                            //Db::name('ranking_records')->insert(['types' => 8, 'user_id' => $user['id'], 'to_user' => $id, 'count' => 1, 'create_time' => time()]);

                            Db::name('user')->where(['id' => $user['id']])->setInc('invite_count');

                            //Db::name('user')->where(['id' => $id])->setField('invite_time', time());

                            // 任务
                            Task::finish('invite', $user['id']);

                            if ($user['proxy'] + 0) {
                                $hongbao = $config['hongbao'];

                                $hongbao = explode(',',$hongbao);

                                $hongbao[1] = $hongbao[1] ?? $hongbao[0];

                                $money = mt_rand($hongbao[0],$hongbao[1]);

                                if ($money + 0) {
                                    Income::index($user['id'], $id, $money, '邀请奖励收益', 1);
                                }
                            }

                            RegModel::parentSay($id, $post['sex'], $post['yqr']);
                        }
                    }

                    /*$request = request();
                    $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

                    $kefu = intval($config['id']);

                    if ($kefu) {
                        $field = $post['sex'] == '男' ? 'welcome_male' : 'welcome_female';
                        $datas = [
                            'userid' => $kefu,
                            'touserid' => $id,
                            'type' => 0,
                            'content' => $config[$field],
                            'single' => 1
                        ];
                        curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                    }*/
                }

                return json(['code' => 200, 'msg' => '注册成功', 'id' => $id]);
            }else{
                return json(['code' => 201, 'msg' => '请选择性别']);
            }
        }
    }


    public function temp()
    {

        $device_id = input('device_id');

        if(!$device_id){
            return $this->miss('未获取到设备信息');
        }
        $token = '';
        $time = time();
        $user = Db::name('user')->master()->where(['device_id' => $device_id, 'reg'=>0])->find();
        $kfid = Db::name('config_system')->where(['title' => 'id'])->value('content');

        $user_real = Db::name('user_device_records')->master()->where(['device_id' => $device_id])->cache(120)->find();

        if($user){
            $tokenData = array(
                'userid' => $user['id'],
                'time' => $time,
            );
            $token = Token::createToken($tokenData);
            if($token['status']==200){
                Db::name('user')->where(['id'=>$user['id']])->update(['last_login_time'=>$time]);
                $token = $token['token'];
            }
            return json(['code' => 200, 'id' => $user['id'], 'kfid'=>(int)$kfid, 'token'=>$token, 'master'=>$user_real ? $user_real['user_id'] : 0]);
        }
        return json(['code' => 201, 'msg' => '不允许游客登录,请用手机号登录']);
        $post['device_id'] = $device_id;
        $post['reg'] = 0;
        $post['sex'] = '男';
        $post['name'] = '游客用户1';
        $post['last_login_time'] = $time;
        $post['head_100'] = $post['head_300'] = $post['head_portrait'] = '/public/style/api/img/female/' . mt_rand(1,20) . '.jpg';
    
        $id = Db::name('user')->insertGetId($post);

        $tokenData = array(
            'userid' => $id,
            'time' => $time,
        );
        $token = Token::createToken($tokenData);
        if($token['status']==200){
            $token = $token['token'];
        }

        return json(['code' => 200, 'id' => (int)$id, 'kfid'=>(int)$kfid, 'token'=>$token, 'master'=>$user_real ? $user_real['id'] : 0]);
    }
    
    private function generateUniqueInviteCode(): string
    {
        $length = 7;
        $maxTries = 10;
        $redisKey = 'invite_code_bitmap';
        $maxValue = pow(10, $length) - 1;

        try {
            $redis = \think\Cache::store('redis')->handler();
            $redis->select(4);
            while ($maxTries-- > 0) {
                // Generate zero-padded numeric code
                $randomNumber = mt_rand(0, $maxValue);
                $inviteCode = str_pad((string)$randomNumber, $length, '0', STR_PAD_LEFT);
                $offset = intval($inviteCode); // Bitmap offset

                // Check if the bit is already set
                if (!$redis->getBit($redisKey, $offset)) {
                    // Mark this invite code as used
                    $redis->setBit($redisKey, $offset, 1);
                    return $inviteCode;
                }
            }
        } catch (\Exception $e) {
            // If we've exhausted all attempts, re-throw the exception
            \think\Log::error('Failed to generate unique invite code: ' . $e->getMessage());
        }

        // 默认返回值，确保函数在所有路径下都有返回值
        return str_pad((string)mt_rand(0, $maxValue), $length, '0', STR_PAD_LEFT);
    }
    
    /**
     * 发放注册金豆奖励
     *
     * @param int $userId 用户ID
     * @param string $sex 用户性别
     * @return bool 是否成功发放
     */
    public static function giveRegisterBeans($userId)
    {
        $giveBean = 200000;
        $giveBeanMsg = '女用户注册赠送金豆' . $giveBean;

        // 开启事务确保数据一致性
        Db::startTrans();
        try {
            // 增加用户金豆
            $resbean = Db::name('user')->where('id', $userId)->setInc('beans', $giveBean);

            if ($resbean === 1) {
                // 记录金豆发放日志
                $beanlog = [
                    'uid' => $userId,
                    'num' => $giveBean,
                    'content' => $giveBeanMsg,
                    'addtime' => date('Y-m-d H:i:s')
                ];
                Db::name('beans_give_records')->insert($beanlog);

                Db::commit();
                return true;
            }

            Db::rollback();
            return false;
        } catch (\Exception $e) {
            Db::rollback();
            // 记录错误日志
            \think\Log::error('发放注册金豆失败: ' . $e->getMessage());
            return false;
        }
    }
    
}